package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.RecommendVideo;
import com.itheima.domain.mongo.Video;
import com.itheima.service.mongo.VideoService;
import com.itheima.utils.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;


/**
 * @author Guanxing
 * @date 2021/9/27
 */
@Service
public class VideoServiceImpl implements VideoService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;

    //查询小视频列表
    @Override
    public PageBeanVo findSmallVideos(Integer pageNum, Integer pageSize, Long loginUserId) {
        int startIndex = (pageNum - 1) * pageSize;
        Query query = new Query(
                Criteria.where("userId").is(loginUserId)
        );
        //查询推荐视频
        List<RecommendVideo> recommendVideoList = mongoTemplate.find(query, RecommendVideo.class);

        List<Video> videoList = new ArrayList<>();
        //转换成video
        for (RecommendVideo recommendVideo : recommendVideoList) {
            Video video = mongoTemplate.findById(recommendVideo.getVideoId(), Video.class);
            //添加到集合
            videoList.add(video);
        }

        long count = mongoTemplate.count(query, RecommendVideo.class);
        return new PageBeanVo(pageNum,pageSize,count,videoList);
    }

    //保存视频
    @Override
    public void saveVideo(Video video) {
        video.setVid(idService.getNextId(ConstantUtil.VIDEO_ID));
        video.setCreated(System.currentTimeMillis());

        mongoTemplate.save(video);
    }

    //查询视频列表
    @Override
    public PageBeanVo findVideoByUid(Integer pageNumber, Integer pageSize, Long uid) {
        int startIndex = (pageNumber -1 ) * pageSize;
        Query query = new Query(
                Criteria.where("userId").is(uid)
        ).with(Sort.by( Sort.Order.desc("date")  ))
                .skip(startIndex).limit(pageSize);
        List<Video> videoList = mongoTemplate.find(query, Video.class);

        long counts = mongoTemplate.count(query, Video.class);

        return new PageBeanVo(pageNumber , pageSize, counts , videoList);
    }

    //根据id查询视频
    @Override
    public Video findVideoById(String videoId) {
        return mongoTemplate.findById(new ObjectId(videoId),Video.class);
    }

}
